const lowdb = require("lowdb");
const path = require("path");
const fs = require("fs");

const StorageAdapter = require('./StorageAdapter');

const { imgFan, deleteFile, createFilePath } = require('./fileUtils')
const CONFIG_FILE = path.join(__dirname, "../../data/config.json");
const DATA_FILE = path.join(__dirname, "../../data/data.json");
const PHOTO = path.join(__dirname, "../../data/photo/");
const { framePath, propPath } = require('./filePath');
createFilePath(framePath);
createFilePath(propPath);
const excelData = [];
const rateData = [];


var CONFIG_STORE = lowdb(new StorageAdapter(CONFIG_FILE));
var DATA_STORE = lowdb(new StorageAdapter(DATA_FILE));


CONFIG_STORE.defaults({
    config: {
        activeUrl: "https://www.mzy-tech.com/active"
    },
    clickPos: "top left 200",
    password: '123',
    algoType: "comic",
    backTime: 10,
    cameraPositon: 100,
    cameraSize: {
        width: 708,
        height: 954
    }
}).write();

_config = CONFIG_STORE.get("config");
const DataManager = {
    getActiveUrl: function () {
        return _config.get("activeUrl").value();
    },
    getIp: function () {
        return _config.get("ip").value();
    },
    getData: () => {
        return DATA_STORE.value();
    },
    savePhoto: (data) => {
        return new Promise((resolve, reject) => {
            const { base64 } = data;
            // 移除Base64图片数据中的头部信息
            const base64Data = base64.replace(/^data:image\/\w+;base64,/, '');
            const bufferData = Buffer.from(base64Data, 'base64');
            const imgPath = path.join(PHOTO, 'preview.jpg');
            // const fanImgpath = path.join(PHOTO, 'fan.jpg');
            // deleteFile(fanImgpath)
            // 将图片数据写入本地文件
            fs.writeFile(imgPath, bufferData, async (err) => {
                if (err) {
                    return reject(err);
                }
                // const res = await imgFan(imgPath, fanImgpath)
                resolve(imgPath);
            });
        });

    },
    getFrameImg: () => {
        return fs.readdirSync(framePath);
    },
    getPropsImg: () => {
        return fs.readdirSync(propPath);
    },
    setConfig: (par, value) => {
        _config.set(par, value).write();
    },
    getConfig: (par) => {
        return _config.get(par).value();
    },
    getAllConfig: () => {
        return CONFIG_STORE.value();
    },
    getExcelData: () => {
        return excelData;
    },
    getExcelRate: () => {
        return rateData;
    },
    saveData: (product, key) => {
        let old = DATA_STORE.get(key).value();
        if (old.length) {
            old.forEach((array) => {
                let has = product.find((_array) => _array.id === array.id);
                DataManager.removeImage(array, has || { certificateList: [] });
            });
        }
        DATA_STORE.set(key, product).write();
    },

};

module.exports = DataManager;
